/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var g_profile;

var g_teams;
var g_schedule;
var g_today;
var g_date;

var TEAMS_URL = 'http://sports.scores.gadget.googlepages.com/euro2008.teams.txt';
var g_teamDataSource;

var SCHEDULE_URL = 'http://sports.scores.gadget.googlepages.com/euro2008.sked.txt';
var g_scheduleDataSource;

var g_checkDateTimer;
var REFRESH_INTERVAL_MS = 2 * 60 * 1000;

var TOURNAMENT_START_UTC = new Date(Date.UTC(2008, 5, 7, 16, 0, 0));
var TOURNAMENT_END_UTC = new Date(Date.UTC(2008, 5, 29, 18, 45, 0));

var MONTH_NAMES = [
  strings.JAN,
  strings.FEB,
  strings.MAR,
  strings.APR,
  strings.MAY,
  strings.JUN,
  strings.JUL,
  strings.AUG,
  strings.SEP,
  strings.OCT,
  strings.NOV,
  strings.DEC];

function onOpen() {
  g_today = new Date();
  g_date = new Date();
  ensureDateBounds();

  g_profile = new Profile();
  g_profile.load();

  centerFlag();
  loadTheme();

  plugin.onShowOptionsDlg = showOptions;

  g_teamDataSource = new DataSource(
      TEAMS_URL, REFRESH_INTERVAL_MS, processTeamData);
  // Creates g_scheduleDataSource after g_teamDataSource loads.
  // See processTeamData.

  g_checkDateTimer = view.setInterval(checkDate, REFRESH_INTERVAL_MS);
  draw();
}

function ensureDateBounds() {
  if (isDateGreater(g_date, TOURNAMENT_END_UTC)) {
    g_date = TOURNAMENT_END_UTC;
  }

  if (isDateLesser(g_date, TOURNAMENT_START_UTC)) {
    g_date = TOURNAMENT_START_UTC;
  }
}

function checkDate() {
  var today = new Date();

  if (!isDateEqual(today, g_today)) {
    g_today = today;
    g_date = g_today;
    ensureDateBounds();
    draw();
  }
}

function draw() {
  dateLabel.innerText =
      MONTH_NAMES[g_date.getMonth()] + ' ' + g_date.getDate();

  content.removeAllElements();

  var matches = getMatches(g_date);

  if (matches.length === 0) {
    drawNoMatches();
  } else {
    for (var i = 0; i < matches.length; ++i) {
      drawMatch(matches[i]);
    }
  }

  resizeHeight(content.children.count * content.itemHeight);
}

function resizeHeight(height) {
  if (height < content.itemHeight) {
    height = content.itemHeight;
  }

  view.height = themeTopPanel.height + height + themeBottomPanel.height;
  content.height = height;

  themeMiddlePanel.height = height;
  containerMiddlePanel.height = height;
  frameMiddlePanel.height = height;

  var bottomY = view.height - themeBottomPanel.height;

  themeBottomPanel.y = bottomY;
  containerBottomPanel.y = bottomY;
  frameBottomPanel.y = bottomY;

  centerFlag();
}

var FLAG_HEIGHT = 67;

function centerFlag() {
  bigFlagPanel.y = (view.height - FLAG_HEIGHT) / 2;
}

function getMatches(date) {
  var matches = [];

  if (!g_schedule) {
    return matches;
  }

  for (var i = 0; i < g_schedule.length; ++i) {
    var match = g_schedule[i];
    if (match.isFallsOnDate(date)) {
      matches.push(match);
    }
  }

  matches.sort(Match.sorter);

  return matches;
}

function drawNoMatches() {
  var newItemXml =
  '<item>' +
    '<label width="100%" height="100%">' + strings.NO_MATCHES + '</label>' +
  '</item>';

  content.appendElement(newItemXml);
}

function drawMatch(match) {
  var newItemXml =
  '<item>' +
    '<img y="3" src="' + match.getAwayIcon() + '"/>' +
    '<img y="18" src="' + match.getHomeIcon() + '"/>' +
    '<label width="90" height="15" x="20">' + match.getAwayName() + '</label>' +
    '<label width="90" height="15" x="20" y="15">' + match.getHomeName() + '</label>' +
    '<label x="110" width="40" height="15">' + match.getAwayScore() + '</label>' +
    '<label x="110" width="40" height="15" y="15">' + match.getHomeScore() + '</label>' +
    '<label x="150" width="34" height="15" align="right">' + match.getTime() + '</label>' +
  '</item>';

  var newItem = content.appendElement(newItemXml);
  newItem.onclick = makeMatchOnClick(match);
  newItem.ondblclick = makeMatchOnDoubleClick(match);
}

function makeMatchOnClick(match) {
  return function() {
    showMatchDetails(match);
  };
}

function makeMatchOnDoubleClick(match) {
  return function() {
    framework.openUrl(match.getNewsLink());
  };
}

var g_currentDetailsViewMatch;

function showMatchDetails(match) {
  var previous = g_currentDetailsViewMatch;

  if (previous) {
    plugin.closeDetailsView();
  }

  if (match == previous) {
    return;
  }

  g_currentDetailsViewMatch = match;

  var detailsView = new DetailsView();

  // Create the details view and set its content.
  detailsView.SetContent(
      '',             // Item's displayed website/news source.
      undefined,      // Time created
      'details.xml',  // The XML file
      false,          // Whether time is shown as absolute time
      0);             // Content layout flags

  detailsView.detailsViewData.putValue('match', match);

  // Show the details view
  plugin.showDetailsView(detailsView,  // The DetailsView object
      match.getTitle(),  // The title
      gddDetailsViewFlagToolbarOpen,  // Flags
      onDetailsViewFeedback);  // The handler to call when details view closes
}

function onDetailsViewFeedback(flags) {
  if (flags == gddDetailsViewFlagToolbarOpen) {
    framework.openUrl(g_currentDetailsViewMatch.getNewsLink());
  }

  g_currentDetailsViewMatch = null;
}

function processTeamData(responseText) {
  g_teams = Team.parseTeams(responseText);

  if (!g_scheduleDataSource) {
    g_scheduleDataSource = new DataSource(
        SCHEDULE_URL, REFRESH_INTERVAL_MS, processScheduleData);
  }
}

function processScheduleData(responseText) {
  g_schedule = Match.parseSchedule(responseText, g_teams);

  // Ensure connecting screen is hidden.
  connectingLabel.visible = false;
  content.visible = true;

  draw();
}

function showOptions(window) {
  var options = new Options(g_profile, TEAMS, onOptionsOk);
  options.show(window);
}

function onOptionsOk(profile) {
  g_profile = profile;
  g_profile.save();
  loadTheme();
  draw();
}

function loadTheme() {
  var teamColor = g_profile.teamColor;
  var frameColor = FRAME_COLORS[teamColor];
  var titleColor = TITLE_COLORS[teamColor];

  themeTopPanel.background = frameColor;
  themeMiddlePanel.background = frameColor;
  themeBottomPanel.background = frameColor;

  dateLabel.color = titleColor;

  bigFlagPanel.src = getTeamFlag(teamColor);
}

function getTeamFlag(name) {
  return 'images/' + name.substr(0, 3) + '_big.gif';
}

function onPreviousClick() {
  g_date = new Date(g_date.getFullYear(),
                    g_date.getMonth(),
                    g_date.getDate() - 1);
  ensureDateBounds();
  draw();
}

function onNextClick() {
  g_date = new Date(g_date.getFullYear(),
                    g_date.getMonth(),
                    g_date.getDate() + 1);
  ensureDateBounds();
  draw();
}
